package com.cqie.secondhandtransaction.controller;

import com.cqie.secondhandtransaction.DTO.UserDetailsDTO;
import com.cqie.secondhandtransaction.controller.params.LoginParam;
import com.cqie.secondhandtransaction.controller.params.RegisterParam;
import com.cqie.secondhandtransaction.model.Result;
import com.cqie.secondhandtransaction.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@Api(value = "登录/注册", tags = {"登录/注册"})
public class LoginController extends BaseController {
    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("/login")
    @ApiOperation(value = "登录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<UserDetailsDTO> login(@RequestBody @Validated LoginParam param) {
        return response(userInfoService.login(param));
    }

    @PostMapping("/register")
    @ApiOperation(value = "注册", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<Void> register(@ModelAttribute @Validated RegisterParam param, @RequestParam(value = "picture", required = false) MultipartFile picture) {
        userInfoService.register(param, picture);
        return response();
    }

    @PostMapping("/outLogin")
    @ApiOperation(value = "登出", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<Void> logout(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return response();
    }

}
